<template>
  <view class="message-container">
    <!-- 顶部消息类型筛选 -->
    <view class="filter-section">
      <scroll-view scroll-x="true" class="filter-scroll">
        <view 
          v-for="(type, index) in noticeTypes" 
          :key="index" 
          class="filter-item" 
          :class="{ active: currentType === type.id }"
          @click="setCurrentType(type.id)"
        >
          {{ type.type }}
        </view>
      </scroll-view>
    </view>
    
    <!-- 消息列表 -->
    <view class="message-list" v-if="messageList.length > 0">
      <view 
        v-for="(item, index) in filteredMessages" 
        :key="index" 
        class="message-item"
        @click="readMessage(item)"
      >
        <view class="message-header">
          <view class="message-title">{{ item.title }}</view>
          <view class="message-time">{{ formatTime(item.publish_time) }}</view>
        </view>
        <view class="message-content">{{ item.content }}</view>
        <view class="message-footer">
          <view class="message-publisher">{{ item.publisher }}</view>
          <image 
            v-if="item.file_url" 
            src="/static/icons/file.png" 
            class="file-icon" 
            @click.stop="openInBrowser(item.file_url)"
          ></image>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <view class="empty-text">暂无消息</view>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js'

export default {
  name: 'MessageIndex',
  data() {
    return {
      noticeTypes: [], // 消息类型
      currentType: 0, // 当前选中的类型，0表示全部
      messageList: [], // 消息列表
      loading: false
    }
  },
  computed: {
    filteredMessages() {
      console.log('当前类型:', this.currentType, '消息列表:', this.messageList); // 添加调试日志
      
      if (this.currentType === 0) {
        return this.messageList;
      } else {
        // 确保使用数字类型比较
        return this.messageList.filter(item => {
          const itemTypeId = Number(item.notice_type_id);
          const currentTypeId = Number(this.currentType);
          return itemTypeId === currentTypeId;
        });
      }
    }
  },
  onLoad() {
    this.getNoticeTypes();
    this.getMessageList();
  },
  methods: {
    // 获取消息类型
    async getNoticeTypes() {
      try {
        const res = await request({
          url: 'notice-server/notice/types',
          method: 'GET'
        });
        
        if (res.code === 200) {
          // 如果后端使用的是驼峰命名，需要转换
          this.noticeTypes = [{id: 0, type: '全部'}].concat(
            res.data.map(item => ({
              id: item.id || item.typeId, // 检查可能的字段名
              type: item.type || item.typeName // 检查可能的字段名
            }))
          );
        } else {
          // 手动设置，确保新闻通知ID为2
          this.noticeTypes = [
            {id: 0, type: '全部'},
            {id: 1, type: '活动通知'},
            {id: 2, type: '新闻通知'}, // 确保ID为2
            {id: 3, type: '紧急通知'},
            {id: 4, type: '维修通知'},
            {id: 5, type: '缴费通知'}
          ];
        }
      } catch (error) {
        // 同样确保新闻通知ID为2
        this.noticeTypes = [
          {id: 0, type: '全部'},
          {id: 1, type: '活动通知'},
          {id: 2, type: '新闻通知'}, // 确保ID为2
          {id: 3, type: '紧急通知'},
          {id: 4, type: '维修通知'},
          {id: 5, type: '缴费通知'}
        ];
      }
    },
    
    // 获取消息列表
    async getMessageList() {
      this.loading = true;
      try {
        const res = await request({
          url: 'notice-server/notice/list',
          method: 'GET'
        });
        
        this.loading = false;
        if (res.code === 200) {
          // 转换字段名称
          this.messageList = res.data.map(item => {
            return {
              id: item.id,
              title: item.title,
              content: item.content,
              notice_type_id: item.noticeTypeId, // 注意这里转换驼峰为下划线
              publisher: item.publisher,
              publish_time: item.publishTime, // 注意这里转换驼峰为下划线
              status: item.status,
              file_url: item.fileUrl || item.file_url, // 添加附件URL字段
              filename: item.filename // 添加附件名称字段
            };
          });
        } else {
          uni.showToast({
            title: '获取消息列表失败',
            icon: 'none'
          });
          // 模拟数据，实际开发中应该删除
          this.messageList = [];
        }
      } catch (error) {
        this.loading = false;
        console.error('获取消息列表出错:', error);
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        // 模拟数据，实际开发中应该删除
        this.messageList = [];
      }
    },
    
    // 设置当前消息类型
    setCurrentType(typeId) {
      console.log('选择类型:', typeId); // 调试日志
      this.currentType = Number(typeId); // 确保转换为数字
    },
    
    // 阅读消息
    async readMessage(message) {
      // 跳转到消息详情页
      uni.navigateTo({
        url: `/pages/message/detail?id=${message.id}`
      });
    },
    
    // 使用系统浏览器打开附件
    openInBrowser(url) {
      // 阻止事件冒泡
      event.stopPropagation();
      
      if (!url) return;
      
      // 确保URL格式正确
      if (!url.startsWith('http')) {
        url = 'http://' + url;
      }
      
      // 判断平台环境，使用条件编译
      // #ifdef APP-PLUS
      plus.runtime.openURL(url, (err) => {
        if (err) {
          uni.showToast({
            title: '无法打开浏览器',
            icon: 'none'
          });
        }
      });
      // #endif
      
      // #ifdef H5
      try {
        window.open(url, '_system');
      } catch (error) {
        console.error('打开URL失败:', error);
        uni.showToast({
          title: '无法打开链接',
          icon: 'none'
        });
      }
      // #endif
      
      // #ifdef MP
      uni.showToast({
        title: '小程序环境不支持直接打开外部链接',
        icon: 'none'
      });
      // #endif
    },
    
    // 格式化时间
    formatTime(timeStr) {
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      
      // 小于一天显示"今天 HH:MM"
      if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `今天 ${hours}:${minutes}`;
      }
      
      // 小于一年显示"MM-DD"
      if (diff < 365 * 24 * 60 * 60 * 1000) {
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
      }
      
      // 其他显示"YYYY-MM-DD"
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped>
.message-container {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.filter-section {
  background-color: #ffffff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.filter-scroll {
  white-space: nowrap;
  padding: 0 20rpx;
}

.filter-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
}

.filter-item.active {
  background-color: #1a7cf7;
  color: #fff;
}

.message-list {
  padding: 20rpx;
}

.message-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.message-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.message-time {
  font-size: 24rpx;
  color: #999;
}

.message-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
}

.message-publisher {
  color: #999;
}

.file-icon {
  width: 36rpx;
  height: 36rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style> 